package com.example.baseutils

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.util.Log

/**
 *自定义顶层函数，用于集成SharedPreferences工具
 * */
var SP_NAME = "ddn_help_sp"
lateinit var MySharedPreferences: SharedPreferences
fun initSharedPrefer(context: Application, spName:String= SP_NAME) {
    SP_NAME= spName
    MySharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE)
    Log.e("TAG", "initSharedPrefer: ")
}

/**
 * 定义一个SharedPreferences的内联高阶扩展函数，用于保存
 * 避免每次都要新建SharedPreferences和重复apply操作
 * */
inline fun SharedPreferences.save(block: SharedPreferences.Editor.() -> Unit) {
    val edit = edit()
    edit.block()
    edit.apply()

}


fun SharedPreferences.read(key: String, defualtValue: Boolean = false): Boolean =
    getBoolean(key, defualtValue)

fun SharedPreferences.read(key: String, defualtValue: String): String? =
    getString(key, defualtValue)

fun SharedPreferences.read(key: String, defualtValue: Float = 0.0f): Float =
    getFloat(key, defualtValue)

fun SharedPreferences.read(key: String, defualtValue: Int = 0): Int = getInt(key, defualtValue)
fun SharedPreferences.read(key: String, defualtValue: Long = 0L): Long = getLong(key, defualtValue)
